function AllReady() {
    var mstform = Ext.getCmp("PoUrgeM"); //获取容器
    var PhidPc = mstform.queryById("PhidPc");
    var PhidCnt = mstform.queryById("PhidContract");
    var dgrid = Ext.getCmp("PoUrgeD");
    var Toolbar = Ext.getCmp("toolbar");
    var dstore = dgrid.store;
    var user_pro_type = mstform.queryById("user_pro_type");
    var user_ywlx = mstform.queryById("user_ywlx");
    var PhidBuyer = mstform.queryById("PhidBuyer");
    var user_regional_center = mstform.queryById("user_regional_center");
    var user_division = mstform.queryById("user_division"); //获取字段
    var user_product_line = mstform.queryById("user_product_line");
    var TotalMony = mstform.queryById("TotalMony");
    var TotalTaxMony = mstform.queryById("TotalTaxMony");
    var user_tax_amt = mstform.queryById("user_tax_amt");
    var PhidBuyer = mstform.queryById("PhidBuyer");
    var BuyerPhone = mstform.queryById("BuyerPhone");
    var PhidOrderDept = mstform.queryById("PhidOrderDept");
    var user_gys = mstform.queryById("user_gys");

    PhidCnt.addListener("helpselected", function () {
        // console.log("PhidCnt change event fired");
        execServer("getCntInfo", { cnt: PhidCnt.getValue() }, function (res) {
            const datasGetCntInfo = JSON.parse(res.data)[0].extendObjects;
            if (datasGetCntInfo) {
                if (datasGetCntInfo.pc) {
                    console.log(
                        datasGetCntInfo.pc,
                        "PhidPc.setValue(datasGetCntInfo?.pc"
                    );

                    PhidPc.setValue(datasGetCntInfo?.pc);
                    BatchBindCombox([PhidPc]);
                }
                if (datasGetCntInfo.upt) {
                    user_pro_type.setValue(datasGetCntInfo.upt);
                }
                if (datasGetCntInfo.ubt) {
                    user_ywlx.setValue(datasGetCntInfo.ubt);
                    BatchBindCombox([user_ywlx]);
                }
                if (datasGetCntInfo.up) {
                    PhidBuyer.setValue(datasGetCntInfo.up);
                    BatchBindCombox([PhidBuyer]);
                }
            }
        });
    });
    PhidBuyer.addListener("change", function (args) {
        // console.log(args.value, "采购员");
        execServer("getModileYHD", { phidPhonea: args.value }, function (res) {
            try {
                var obj = JSON.parse(res.data);
                BuyerPhone.setValue(obj[0].extendObjects.mobile1);
            } catch (error) { }
        });
    });
    PhidPc.addListener("change", function (args) {
        if (PhidPc.getValue()) {
            getSyQty(mstform.queryById("PhidPc").getValue())
        
            //----------
            execServer(
                "getPtInfoByPhid",
                { phid: PhidPc.getValue() },
                function (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    //帮助字段赋值
                    // console.log(datas, "datas");
                    user_division.setValue(datas.division_phid);
                    user_product_line.setValue(datas.midwife_phid);
                    user_regional_center.setValue(datas.regional_center_phid);
                    BatchBindCombox([user_division]);
                    BatchBindCombox([user_product_line]);
                    BatchBindCombox([user_regional_center]);
                }
            );

            // console.log(PhidCnt.getValue(), "PhidPc");
            if (!PhidCnt.getValue()) return;
            execServer(
                "getCntMInfoByPhid",
                { phid: PhidCnt.getValue() },
                function (res) {
                    try {
                        const datasGetCntMInfoByPhid = JSON.parse(res.data)[0]
                            .extendObjects;
                        //帮助字段赋值
                        // console.log(datasGetCntMInfoByPhid.dept_phid, "getCntMInfoByPhid");
                        PhidOrderDept.setValue(datasGetCntMInfoByPhid.dept_phid);
                        BatchBindCombox([PhidOrderDept]);
                        user_gys.setValue(datasGetCntMInfoByPhid.supply_id);
                        BatchBindCombox([user_gys]);
                    } catch (error) { }
                }
            );
        }
    });

    TotalMony.addListener("change", function () {
        user_tax_amt.setValue(TotalTaxMony.getValue() - TotalMony.getValue());
    });
    TotalTaxMony.addListener("change", function () {
        user_tax_amt.setValue(TotalTaxMony.getValue() - TotalMony.getValue());
    });



        // 用于状态是否发生变化
        let current = otype
        dstore.on("datachanged", async function (dstore, eOpts) {
            mstform.on("dataready",async ()=>{
                console.log(`PhId`,mstform.queryById("PhId").getValue());
                if(current != otype){
                    current = otype
                    await getSyQty(mstform.queryById("PhidPc").getValue())
                }
                setDgridValue(dstore)
            })

            if(otype != 'add') return 
            setDgridValue(dstore)
        });

        function setDgridValue(dstore){
            if(otype == 'add'|| otype == 'edit'){
                const records = dstore.getRange();
                for (const record of records) {
                    //添加剩余量字段
                    record.set("user_shsjljsl",window.qtytotal[record.get("PhidItemData")])
                    if(!record.get("Qty")){
                        record.set("Qty",window.qtytotal[record.get("PhidItemData")]);
                      record.set("ConfirmQty",record.get("Qty"));
                      
                    }
                    try {
                        // console.log(record.data.PhidItemData, "物料id");
                        // console.log(record.data.PhidItemid, "物料id");
                        execServer(
                            "GETitemzq",
                            {
                                phid: record.data.PhidItemData,
                            },
                            function (res) {
                                // console.log(res, "res");
                                try {
                                    const obj = JSON.parse(res.data)[0].extendObjects;
                                    if (!obj.pur_lead) return; //如果为空则不执行
                                    record.set(
                                        "user_ckarrival_dt",
                                        addDaysToDate(new Date(), obj.pur_lead)
                                    );
                                    if (otype != 'add') record.commit();
                                } catch (error) { }
                            }
                        );
                    } catch (error) { }
                }
                dgrid.getView().refresh()
            }
        
        }


    //监听表体编辑
    dgrid.addListener('edit',(dt,e)=>{
        const dstore = e.record
        console.log('监听读取',dstore);
        edit(dstore)
    })

    //编辑逻辑
    function edit(dstore){
        if(!dstore.get("PhidItemid")) return
        const phidItem = dstore.get("PhidItemData")
        const Qty = dstore.get("Qty")
        const phid_pc = mstform.queryById("PhidPc").getValue() 
        console.log(`缓冲`,window.qtytotal,phidItem,phid_pc);
        if((Number(window.qtytotal[phidItem]) || 0) < Qty){
            Ext.Msg.alert("提示","要货数量超出！当前剩余："+dstore.get("user_shsjljsl"))
            dstore.set("Qty",0)
            dstore.set("ConfirmQty",0)
        }
        // 判断数量是否超出(无缓冲去查找)
        dgrid.getView().refresh()
    }
    //查找当前物料可用数量
    getSyQty(mstform.queryById("PhidPc").getValue())
    async function getSyQty(phid_pc) {
        console.log(phid_pc,'项目状态');
        if(!phid_pc) return
        //查找可用数量
        await execServer("getYhdQtyByPhidPcAndItem", { phid_pc },async (res) => {
            console.log(`累计数量`, res);
            if (res.count == 0) {
                window.qtytotal= {}
                return 
            } else {
                let total = JSON.parse(res.data).reduce((value,item)=>{
                    value[item.extendObjects.phiditem] = item.extendObjects.qty
                    return value
                },{})
                console.log(`mstform.getItem("PhId").getValue()`,mstform.getItem("PhId").getValue());
                const phid = mstform.getItem("PhId").getValue()?mstform.getItem("PhId").getValue():'10086'
                //查询累计用过数量
                await execServer("getYhdPhidItemTotalQty", { phid_pc,phid }, (res) => {
                    console.log(`累计用过数量`, res);
                    let ysy = {}
                    if (res.count == 0) {
                    } else {
                        const _data = JSON.parse(res.data)
                        ysy = _data.reduce((value,item)=>{
                            value[item.extendObjects.phiditem] = item.extendObjects.qty
                            return value;
                        },{})
                    }
                    // 处理结果，搞出来剩余量
                    window.qtytotal = {}
                    for(let key in total){
                        console.log(key,total[key],ysy[key]);
                        window.qtytotal[key] = (Number(total[key]) || 0) - (Number(ysy[key]) || 0)
                    }
                    console.log(`qtytotal`,window.qtytotal);
                })
            }
        })
    }
} //End -- AllReady

function addDaysToDate(date, days) {
    // 将传入的日期字符串转换为Date对象，如果本身就是Date对象则直接使用
    let targetDate = date instanceof Date ? date : new Date(date);
    // 获取时间戳，单位是毫秒，然后加上天数对应的毫秒数
    targetDate.setTime(targetDate.getTime() + days * 24 * 60 * 60 * 1000);
    return targetDate;
}

// function beforeSaveEdit() {
//     var mstform = Ext.getCmp("PoUrgeM"); //获取容器
//     var PhidPc = mstform.queryById("PhidPc");
//     execServer("getRkYhInfo", { pc: PhidPc }, function (res) {
        // console.log(res);
//         const data = JSON.parse(res.data);
//         const ce = data[0].extendObjects.ce;
//         if (ce) {
//             Ext.Msg.alert('提示', "111")
//             return false;
//         } else {

//         }
//     });
// }